package cz.semjob.document.processing;

import cz.semjob.linguistic.data.LinguisticWord;

public class DocumentWord implements IIndexedPart {
	
	

	private final DocumentSentence sentence;
	
	private final LinguisticWord linguisticWord;
	
	private int startIndex;
	
	private int endIndex;
	
	/* the word this word is dependent to */
	private DocumentWord dependecyWord;
	
	private Integer dependecyIndex;

	public DocumentWord(LinguisticWord linguisticWord, DocumentSentence sentence) {
		super();
		this.linguisticWord = linguisticWord;
		this.sentence = sentence;
	}
	
	public DocumentWord getDependencyWord() {
		if (dependecyWord == null) {
			dependecyWord = findDependencyWord(linguisticWord, sentence);
		}
		return dependecyWord;
	}
	
	public Integer getDependencyIndex() {
		if (dependecyIndex == null) {
			int step = 0;
			DocumentWord currentHead = getDependencyWord();
			while (currentHead != null) {
				currentHead = currentHead.getDependencyWord();
				step++;
			}
			dependecyIndex = step;
		}
		return dependecyIndex;
	}

	private DocumentWord findDependencyWord(LinguisticWord linguisticWord,
			DocumentSentence sentence) {
		int headIndex = linguisticWord.getParserAttribute().getHeadIndex().getAttrValue();
		for (DocumentWord word : sentence.getWords()) {
			if (word.getSentenceIndex() == headIndex-1) {
				return word;
			}
			
		}
		return null;
	}
	
	public int getStartIndex() {
		return startIndex;
	}

	public int getEndIndex() {
		return endIndex;
	}
	
	public String getText() {
		return linguisticWord.getWord();
	}
	
	public int getLength() {
		return linguisticWord.getWord().length();
	}

	public LinguisticWord getLinguisticWord() {
		return linguisticWord;
	}
	
	/** Starts from 0 */
	public int getSentenceIndex() {
		return sentence.getWords().indexOf(this);
	}

	public void setIndexes(int startIndex, int endIndex) {
		this.startIndex = startIndex;
		this.endIndex = endIndex;
	}
	
	public DocumentSentence getSentence() {
		return sentence;
	}


	
	@Override
	public String toString() {
		return "DocumentWord ["+linguisticWord.getWord()+"]";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((linguisticWord == null) ? 0 : linguisticWord.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		DocumentWord other = (DocumentWord) obj;
		if (linguisticWord == null) {
			if (other.linguisticWord != null)
				return false;
		} else if (!linguisticWord.equals(other.linguisticWord))
			return false;
		return true;
	}
	
	

	

}
